package fr.emse.tatiana.corpus;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.*;

import fr.emse.tatiana.display.DisplayCell;
import fr.emse.tatiana.display.DisplayDate;
import fr.emse.tatiana.display.DisplayFileWriter;
import fr.emse.tatiana.replayable.Anchor;
import fr.emse.tatiana.replayable.ReplayableEvent;

import au.com.bytecode.opencsv.CSVReader;

public class CSVWriter {
	
	String xmlname;

	public CSVWriter(String xmlname) {
		this.xmlname = xmlname;
	}

	public void convert(String path,String docname) {
		String startFile = path;
	    String outFile = xmlname;
        DisplayFileWriter writer = new DisplayFileWriter(xmlname);
        
	    try {
	        CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(startFile), "UTF-8"));
	        String[] line = null;

	        String[] header = reader.readNext();

	        int pos = 0;
	        while((line = reader.readNext())!=null){
	        	pos++;
	        	writer.newItem();
	        	boolean hasid = false;
	        	for (int i = 0; i < header.length; i++) {
	        		String colname = header[i];
	        		String val = line[i];
	        		if ("created_at".equals(colname)) {
	        			String[] datetime = val.split(" ");
	        			String[] hms = datetime[1].split(":");
	        			int hour = Integer.parseInt(hms[0]);
	        			int min = Integer.parseInt(hms[1]);           
	        			int sec = Integer.parseInt(hms[2]);  
	        			String[] ymd = datetime[0].split("-");
	        			int year = Integer.parseInt(ymd[0]);
	        			int month = Integer.parseInt(ymd[1]);
	        			int day = Integer.parseInt(ymd[2]);
	        			Calendar cal = Calendar.getInstance();
	        			cal.set(year, month, day, hour, min, sec);
	        			long millis = cal.getTimeInMillis();
	        			writer.newInfo("time", "", new DisplayDate(millis,0));
	        		} else if ("Time".equals(colname)){
	        			writer.newInfo("time", "", new DisplayDate(Long.parseLong(val),0));
	        		} else if ("time".equals(colname)){
	        			String[] hms = val.split(":");
	        			int hour = Integer.parseInt(hms[0]);
	        			int min = Integer.parseInt(hms[1]);           
	        			int msec = (int) (Float.parseFloat(hms[2])*1000);  
		        		writer.newInfo("time", "", new DisplayDate(((hour*60)+min)*60000+msec,0));
	        		} else if ("MessageUrl".equals(colname)){
	        			writer.newInfoFromString("src-anchor", new Anchor(val).toString());
	        			writer.newInfo(colname, "", val);
	        			hasid = true;
	        		} else {
	        			writer.newInfo(colname, "", val);
	        		}
	        	}
	        	if (!hasid) writer.newInfoFromString("src-anchor", new Anchor(docname,pos).toString());
	        }
	        writer.close();
	        
	    } catch (Exception e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
	    }
	
	}
		
}


